package redisutil

import (
	"context"
	"fmt"

	"gitee.com/night-tc/gobige/common"
	"gitee.com/night-tc/gobige/global"
	"gitee.com/night-tc/gobige/redislib"
	"github.com/redis/go-redis/v9"
)

/*
玩家登录后，链接gateway服务器必要的数据
*/
type GateSession struct {
	key string
	//获取redis操作的方法
	GetRedisF func() *redislib.RedisHandleModel
}

func NewGateSession(pid uint64) *GateSession {
	return &GateSession{
		key:       fmt.Sprintf("GateSess:%d", pid),
		GetRedisF: global.GetRedisAccess(global.RedisName_Session).GetConn,
	}
}

const (
	GateSession_Key_PlayerID  = "playerid"
	GateSession_Key_GroupID   = "groupid"
	GateSession_Key_UserID    = "userid"
	GateSession_Key_OpenID    = "openid"
	GateSession_Key_ChannelID = "channelid"

	GateSession_Key_Gateway   = "gateway"
	GateSession_Key_Addr      = "addr"
	GateSession_Key_Token     = "token"
	GateSession_Key_Timestamp = "timestamp"
	GeteSession_Key_EntityID  = "entityid"
)

func (this *GateSession) SaveInfo(rd redis.Cmdable, v map[string]any) error {
	if rd == nil {
		rd = this.GetRedisF()
	}
	defer rd.Expire(context.Background(), this.key, global.Expire3Day)
	return rd.HMSet(context.Background(), this.key, v).Err()
}
func (this *GateSession) GetInfo(rd redis.Cmdable) (common.GMap, error) {
	if rd == nil {
		rd = this.GetRedisF()
	}
	return rd.HGetAll(context.Background(), this.key).Result()
}

// 刷新过期时间
func (this *GateSession) Expire() {
	c := this.GetRedisF()
	c.Expire(c.Ctx, this.key, global.Expire3Day)
}
func (this *GateSession) GetKey() string {
	return this.key
}

// 获取角色会话ID
func (this *GateSession) GetEntityID() (uint64, error) {
	c := this.GetRedisF()
	return c.HGet(context.Background(), this.key, GeteSession_Key_EntityID).Uint64()
}
